package com.lc.projects.unit.thread.part03.test1;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

//等到多个并发事件的完成 CountDownLatch
public class Test3 {
	public static void main(String[] args) {
		Videoconference videoconference = new Videoconference(10);
		Thread threadConference = new Thread(videoconference);
		threadConference.start();

		for (int i = 0; i < 10; i++) {
			Participant p = new Participant(videoconference, "P" + i);
			Thread t = new Thread(p);
			t.start();
		}

	}
}

class Videoconference implements Runnable {

	private final CountDownLatch controller;

	public Videoconference(int count) {
		controller = new CountDownLatch(count);
	}

	public void arrive(String name) {
		System.out.println("Arrived:" + name);
		controller.countDown();
		System.out.println("Wait for other " + controller.getCount());
	}

	@Override
	public void run() {
		try {
			System.out.println("Init Video Meeting: wait for " + controller.getCount());
			controller.await();
			System.out.println("All has done. Let's start!");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

class Participant implements Runnable {
	private Videoconference videoconference;
	private String name;

	public Participant(Videoconference videoconference, String name) {
		super();
		this.videoconference = videoconference;
		this.name = name;
	}

	@Override
	public void run() {
		long duration = (long) (Math.random() * 20);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (Exception e) {
			e.printStackTrace();
		}
		videoconference.arrive(name);
	}

}
